const https = require('https')
const path = require('path')

function doBuildPages (config) {
  console.log(`正在请求构建gitee.com/${config.owner}/${config.repo}仓库的Pages服务`)
  const body = JSON.stringify({
    access_token: config.access_token
  })
  const req = https.request({
    hostname: 'gitee.com',
    port: 443,
    path: `/api/v5/repos/${config.owner}/${config.repo}/pages/builds`,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(body)
    }
  }, (res) => {
    res.setEncoding('utf8')
    let body = ''
    res.on('data', (chunk) => {
      body += chunk
    });
    res.on('end', () => {
      const data = JSON.parse(body)
      if (data.status === 'queued') {
        console.log(`请求成功：正在排队等候部署(${data.url})`)
      } else if (data.notice) {
        console.error(`请求失败：${data.notice}`)
      } else {
        console.warn('未知返回', data)
      }
    });
  })
  req.on('error', (err) => {
    console.error(err)
  })
  req.write(body)
  req.end()
}

module.exports = {
  command: 'build-pages',
  describe: 'make a get HTTP request',
  builder: {
    config: {
      describe: '自动构建Pages所需的配置文件，包含access_token、owner、repo字段。详情见：https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoPagesBuilds'
    },
    access_token: {},
    owner: {},
    repo: {}
  },
  handler: function (argv) {
    let config = {}
    if (argv.config) {
      try {
        config = {
          ...config,
          ...require(path.join(process.cwd(), argv.config))
        }
      } catch (err) {
        console.error(err)
      }
    }
    if (argv.access_token) {
      config.access_token = argv.access_token
    }
    if (argv.owner) {
      config.owner = argv.owner
    }
    if (argv.repo) {
      config.repo = argv.repo
    }
    if (!config.access_token || !config.owner || !config.repo) {
      throw new Error('参数不全')
    }
    doBuildPages(config)
  }
}
